package com.enjoyor.soa.traffic.frame.handler.mybatis;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.spatial.geometry.JGeometry;
import oracle.sql.STRUCT;

import org.apache.commons.dbcp.DelegatingPreparedStatement;
import org.apache.commons.dbcp.PoolableConnection;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl;

@MappedTypes({ JGeometry.class })
@MappedJdbcTypes({ JdbcType.STRUCT })
public class SdoGeometryTypeHandler implements TypeHandler<JGeometry> {

    @Override
    public void setParameter(PreparedStatement ps, int i, JGeometry parameter, JdbcType jdbcType) throws SQLException {
        try {

            Connection conn = ps.getConnection();

            if (ps instanceof DelegatingPreparedStatement) {
                DelegatingPreparedStatement dps = (DelegatingPreparedStatement) ((DelegatingPreparedStatement) ps)
                        .getDelegate();
                conn = dps.getConnection();
            }

            if (conn instanceof PoolableConnection) {
                conn = ((PoolableConnection) conn).getInnermostDelegate();
            }

            if (conn instanceof DruidPooledConnection) {
                conn = ((ConnectionProxyImpl) ((DruidPooledConnection) conn).getConnection()).getConnectionRaw();
            }

            STRUCT dbObject = JGeometry.store(parameter, conn);
            ps.setObject(i, dbObject);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public JGeometry getResult(ResultSet rs, String columnName) throws SQLException {
        // TODO Auto-generated method stub
        STRUCT st = (STRUCT) rs.getObject(columnName);
        if (st != null) {
            return JGeometry.load(st);
        }
        return null;
    }

    @Override
    public JGeometry getResult(ResultSet rs, int columnIndex) throws SQLException {
        // TODO Auto-generated method stub
        STRUCT st = (STRUCT) rs.getObject(columnIndex);
        if (st != null) {
            return JGeometry.load(st);
        }
        return null;
    }

    @Override
    public JGeometry getResult(CallableStatement cs, int columnIndex) throws SQLException {
        // TODO Auto-generated method stub
        STRUCT st = (STRUCT) cs.getObject(columnIndex);
        if (st != null) {
            return JGeometry.load(st);
        }
        return null;
    }
}